package midway.madness;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import midway.madness.post.PostObject;
import midway.madness.post.article.ArticlesListAdapter;
import midway.madness.utils.ApplicationEx;
import midway.madness.utils.SplashScreen;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class SearchActivity extends Activity{
	
	private List<PostObject> posts;
	private SplashScreen splash;
	private Handler handler;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		splash = new SplashScreen(SearchActivity.this);
		splash.showSplash();
		
		setContentView(R.layout.search_results);
		handler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what){
				case ApplicationEx.HANDLE_ERR:
					ApplicationEx appEx = (ApplicationEx) getApplication();
		    		AlertDialog alert = appEx.handleError(SearchActivity.this, msg.getData().getString("errorMsg"));
		    		alert.setOnDismissListener(new OnDismissListener() {
						
						public void onDismiss(DialogInterface dialog) {
							SearchActivity.this.finish();
						}
					});
		    		splash.removeSplash();
		    		alert.show();
					break;
				default:
					super.handleMessage(msg);
					break;
				}
			}
			
		};
		new SearchResults().execute(getIntent().getStringExtra("searchText"));
	}
	
	private class SearchResults extends AsyncTask<String, Void, Void>{

		@Override
		protected Void doInBackground(String... params) {
			String searchText = params[0];
			((TextView)findViewById(R.id.search_results_label)).setText("Search results for: " + searchText);
			search(searchText.trim());
			return null;
		}
		
		protected void onPostExecute(Void v){
			final ListView listView = (ListView) findViewById(R.id.search_list_view);
			listView.setAdapter(new ArticlesListAdapter(SearchActivity.this, android.R.layout.simple_list_item_1, posts));
			listView.setTextFilterEnabled(true);
			listView.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> adapterView, View view,
						int pos, long id) {
					PostObject obj = posts.get(pos);
					obj.goForIntent();
				}
				
			});
			splash.removeSplash();
			if (null == posts || posts.isEmpty()){
				AlertDialog.Builder builder = new Builder(SearchActivity.this);
				builder.setNeutralButton("Okay.", new OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						SearchActivity.this.finish();
					}
				});
				builder.setMessage("Your search did not yield any results.  Please try again.");
				builder.show();
			}
		}

	}
	
	private void search(String trim) {
		if (!trim.equals("")){
			posts = new ArrayList<PostObject>();
			JSONObject obj = null;
			JSONArray temp = null;
			try {
				obj = ((ApplicationEx) getApplication()).postJson("http://midwaymadness.com/api/get_search_results/?dev=1", new String[] {"search"}, new String[] {trim});
				if (!obj.getString("status").equals("ok")){
					Bundle data = new Bundle();
		    		data.putString("errorMsg", ((ApplicationEx) getApplication()).getMessage(obj.getString("status")));
		    		Message msg = new Message();
		    		msg.setData(data);
		    		msg.what = ApplicationEx.HANDLE_ERR;
		    		handler.sendMessage(msg);
				}else{
					temp = obj.getJSONArray("posts");
					for (int i = 0; i < temp.length(); i++){
						posts.add(((ApplicationEx) getApplication()).whatAmI(temp.getJSONObject(i)));
					}
				}
			} catch (JSONException e) {
				AlertDialog dialog = ((ApplicationEx) getApplication()).handleError(SearchActivity.this, "reader");
				dialog.setOnDismissListener(new OnDismissListener() {
					
					public void onDismiss(DialogInterface dialog) {
						splash.removeSplash();
						SearchActivity.this.finish();
					}
				});
				dialog.show();
			} catch (IOException e) {
				AlertDialog dialog = ((ApplicationEx) getApplication()).handleError(SearchActivity.this, "reader");
				dialog.setOnDismissListener(new OnDismissListener() {
					
					public void onDismiss(DialogInterface dialog) {
						splash.removeSplash();
						SearchActivity.this.finish();
					}
				});
				dialog.show();
			}
		}
	}

}
